/// FileName: home_scaffold
/// Author: admin
/// Date: 2021-07-23 18:48
/// Description:

import 'package:flutter/material.dart';
import 'package:high_help_apps/common/apis/v1/user.dart';
import 'package:high_help_apps/common/entities/user/user_profile_response_entity.dart';
import 'package:high_help_apps/common/utils/toast.dart';
import 'package:high_help_apps/common/values/colors.dart';
import 'package:high_help_apps/pages/main/community/community_view.dart';
import 'package:high_help_apps/pages/main/home/home_view.dart';
import 'package:high_help_apps/pages/main/search/search_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../global.dart';

class HomeScaffold extends StatefulWidget {
  @override
  _HomeScaffoldState createState() => _HomeScaffoldState();
}

class _HomeScaffoldState extends State<HomeScaffold> {
  int _currentIndex = 0;

  String _userNickname = '';
  String _userEmail = '';
  String _userAvatar = '';

  final List<Widget> _bottomBarViewList = [
    // 主页， 即 底部导航中 小房子图标的页面
    HomePage(),
    // 搜索页 即 底部导航中 放大镜图标的页面
    SearchPage(),
    // 讨论社区页
    CommunityPage(),
  ];

  final List<BottomNavigationBarItem> _bottomBarList = [
    BottomNavigationBarItem(
        icon: Image.asset(
          "assets/images/icons/tabbar/home_unselected.png",
          fit: BoxFit.cover,
          width: 20.r,
          height: 20.r,
        ),
        activeIcon: Image.asset(
          "assets/images/icons/tabbar/home_selected.png",
          fit: BoxFit.cover,
          width: 20.r,
          height: 20.r,
        ),
        label: '互助'),
    BottomNavigationBarItem(
        icon: Image.asset(
          "assets/images/icons/tabbar/search_unselected.png",
          fit: BoxFit.cover,
          width: 20.r,
          height: 20.r,
        ),
        activeIcon: Image.asset(
          "assets/images/icons/tabbar/search_selected.png",
          fit: BoxFit.cover,
          width: 20.r,
          height: 20.r,
        ),
        label: '搜索'),
    BottomNavigationBarItem(
        icon: Image.asset(
          "assets/images/icons/tabbar/community_unselected.png",
          fit: BoxFit.cover,
          width: 20.r,
          height: 20.r,
        ),
        activeIcon: Image.asset(
          "assets/images/icons/tabbar/community_selected.png",
          fit: BoxFit.cover,
          width: 20.r,
          height: 20.r,
        ),
        label: '社区'),
  ];

  late Widget _currentPage;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    loadUserProfile();
  }

  void loadUserProfile() async {
    UserProfileResponseEntity userProfileResponseEntity =
        await UserAPI.getProfile();

    userProfileResponseEntity.detail!.avatar =
        'http://' + userProfileResponseEntity.detail!.avatar!;

    Global.profile = userProfileResponseEntity.detail!;

    Global.saveProfile(userProfileResponseEntity.detail!);

    setState(() {
      _userNickname = Global.profile.nickName!;
      _userAvatar = Global.profile.avatar!;
      _userEmail = Global.profile.email!;
    });
  }

  @override
  Widget build(BuildContext context) {
    _currentPage = _bottomBarViewList[_currentIndex];

    var _lastClickTime;

    return WillPopScope(
        child: Scaffold(
          appBar: _buildUserAppBar(context),
          drawer: _buildUserDrawer(),
          body: _currentPage,
          bottomNavigationBar: BottomNavigationBar(
            type: BottomNavigationBarType.fixed,
            currentIndex: _currentIndex,
            items: _bottomBarList,
            onTap: (index) {
              setState(() {
                _currentIndex = index;
                _currentPage = _bottomBarViewList[_currentIndex];
              });
            },
            fixedColor: AppColors.primaryElement,
          ),
        ),
        onWillPop: () async {
          if (_lastClickTime == null ||
              DateTime.now().difference(_lastClickTime) >
                  Duration(seconds: 2)) {
            _lastClickTime = DateTime.now();
            toastInfo(msg: "再按一次返回键退出应用");
            return false;
          }
          return true;
        });
  }

  PreferredSize _buildUserAppBar(context) => PreferredSize(
        child: AppBar(
          elevation: 0.0,
          titleSpacing: 0.0,
          leading: Builder(
            builder: (BuildContext context) => GestureDetector(
              onTap: () => Scaffold.of(context).openDrawer(),
              child: Padding(
                padding: EdgeInsets.all(5.r),
                child: CircleAvatar(
                  backgroundColor: Colors.black12,
                  backgroundImage: NetworkImage(_userAvatar),
                  radius: 20.r,
                ),
              ),
            ),
          ),
          title: Text(
            _userNickname,
            style: TextStyle(fontSize: 16.sp),
          ),
          shadowColor: Colors.transparent,
        ),
        preferredSize: Size.fromHeight(45.r),
      );

  Drawer _buildUserDrawer() => Drawer(
        child: ListView(
          //抽屉里面一个list部件
          padding: EdgeInsets.all(0), //顶部padding为0
          children: [
            //所有子部件
            UserAccountsDrawerHeader(
              //用户信息栏
              accountName: Text(
                _userNickname,
                style: TextStyle(color: Colors.white),
              ),
              accountEmail: Text(
                _userEmail,
                style: TextStyle(color: Colors.white),
              ),
              currentAccountPicture: CircleAvatar(
                //头像
                backgroundImage: NetworkImage(_userAvatar),
              ), //下拉箭头
              decoration: BoxDecoration(
                //背景图片
                image: DecorationImage(
                    image: NetworkImage(
                        'https://images.unsplash.com/photo-1515041219749-89347f83291a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1267&q=80'),
                    fit: BoxFit.cover //图片不变性裁剪居中显示
                    ),
              ),
            ),
            ListTile(
              leading: SizedBox(
                width: 28.r,
                height: 28.r,
                child:
                    Image.asset('assets/images/icons/profile/profile_fav.png'),
              ),
              title: Text(
                '我的收藏',
                style: TextStyle(fontSize: 14.sp),
              ),
              trailing: Icon(
                Icons.chevron_right,
                color: AppColors.subTextColor67,
              ),
            ),
            ListTile(
              leading: SizedBox(
                width: 28.r,
                height: 28.r,
                child: Image.asset(
                    'assets/images/icons/profile/profile_message.png'),
              ),
              title: Text(
                '我的消息',
                style: TextStyle(fontSize: 14.sp),
              ),
              trailing: Icon(
                Icons.chevron_right,
                color: AppColors.subTextColor67,
              ),
            ),
            ListTile(
              leading: SizedBox(
                width: 28.r,
                height: 28.r,
                child:
                    Image.asset('assets/images/icons/profile/profile_ido.png'),
              ),
              title: Text(
                '我的关注',
                style: TextStyle(fontSize: 14.sp),
              ),
              trailing: Icon(
                Icons.chevron_right,
                color: AppColors.subTextColor67,
              ),
            ),
            Divider(),
            ListTile(
              leading: SizedBox(
                width: 28.r,
                height: 28.r,
                child: Image.asset(
                    'assets/images/icons/profile/profile_settings.png'),
              ),
              title: Text(
                '设置',
                style: TextStyle(fontSize: 14.sp),
              ),
              trailing: Icon(
                Icons.chevron_right,
                color: AppColors.subTextColor67,
              ),
            )
          ],
        ),
      );
}
